﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Threading;
using System.Net;
using System.Net.Sockets;
using System.Globalization;



namespace VEXREDUS_GS_control
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            Console.WriteLine(GetFlightPathID());





            Thread t = new Thread(parser_backgroundthread);
            t.Start();

        }

        private void bt_get_pidlist_fbw_Click(object sender, EventArgs e)
        {
            UdpSend("$G0*41");
        }

        private void bt_pidlist_fbw_Click(object sender, EventArgs e)
        {
            string no_chksum = "$J0," + tb_pidlist_fbw.Text;
            GlobalVar.udpsendstring = no_chksum + "*" + calculate_checksum(no_chksum);
            Form2 form2 = new Form2();
            form2.Show();
        }


        private void bt_get_pidlist_nav1_stab_Click(object sender, EventArgs e)
        {
            UdpSend("$G1*1F");
        }

        private void bt_pidlist_nav1_stab_Click(object sender, EventArgs e)
        {
            string no_chksum = "$J1," + tb_pidlist_nav1_stab.Text;
            GlobalVar.udpsendstring = no_chksum + "*" + calculate_checksum(no_chksum);
            Form2 form2 = new Form2();
            form2.Show();
        }


        private void bt_get_pidlist_nav1_nav_Click(object sender, EventArgs e)
        {
            UdpSend("$G2*FD");
        }

        private void bt_pidlist_nav1_nav_Click(object sender, EventArgs e)
        {
            string no_chksum = "$J2," + tb_pidlist_nav1_nav.Text;
            GlobalVar.udpsendstring = no_chksum + "*" + calculate_checksum(no_chksum);
            Form2 form2 = new Form2();
            form2.Show();
        }

        private void bt_set_setflightplancase_Click(object sender, EventArgs e)
        {
            string no_chksum = "$M" + tb_setflightplancase.Text;
            GlobalVar.udpsendstring = no_chksum + "*" + calculate_checksum(no_chksum);
            Form2 form2 = new Form2();
            form2.Show();
        }

        private void bt_set_base_Click(object sender, EventArgs e)
        {
            CultureInfo en = new CultureInfo("en-US", false);
            string homebase = GlobalVar.current_loc_lat.ToString(en.NumberFormat) + "," + GlobalVar.current_loc_lon.ToString(en.NumberFormat);
            var fs_homebase = File.Open(GlobalVar.homebasefile_path, FileMode.Create, FileAccess.Write, FileShare.Read);
            var sw_homebase = new StreamWriter(fs_homebase);
            sw_homebase.AutoFlush = true;
            sw_homebase.Write(homebase);
            sw_homebase.Close();
            
            
            string no_chksum = "$B";
            GlobalVar.udpsendstring = no_chksum + "*" + calculate_checksum(no_chksum);
            Form2 form2 = new Form2();
            form2.Show();
        }


        private void bt_udpsend_custom_Click(object sender, EventArgs e)
        {
            string no_chksum = tb_udpsend_custom.Text;
            GlobalVar.udpsendstring = no_chksum + "*" + calculate_checksum(no_chksum);
            Form3 form3 = new Form3();
            form3.Show();
        }







        //############################################### Functions ##################################



        public static string calculate_checksum(string msg)
        {
            Console.WriteLine("calculate checksum - in msg: " + msg + "#####");
            byte crc = 0;

            for (int i = 0; i < msg.Length; i++)
            {
                crc = _crc_ibutton_update(crc, (byte)msg[i]);
            }
            Console.WriteLine("calculate checksum - return: " + crc.ToString("X2"));
            return crc.ToString("X2");

        }


        static byte _crc_ibutton_update(int crc, byte data)
        {
            //byte i;
            crc = crc ^ data;
            for (int i = 0; i < 8; i++)
            {
                if ((crc & 0x01) == 0x01)
                {
                    crc = (crc >> 1) ^ 0x8C;
                }
                else
                {
                    crc >>= 1;
                }
            }

            return Convert.ToByte(crc);
        }

        public static void UdpSend(string udpmsg)
        {
            UdpClient u1 = new UdpClient();
            u1.Connect("localhost", 65002);
            u1.Send(ASCIIEncoding.UTF32.GetBytes(udpmsg), ASCIIEncoding.UTF32.GetByteCount(udpmsg));
        }


        //parser
        public void parser_backgroundthread()
        {


            UdpClient u = new UdpClient(65001, AddressFamily.InterNetwork);

            string readData = "";
            string readDatanew = "";

            for (; ; )
            {

                if (u.Available > 0)
                {
                    IPEndPoint e = new IPEndPoint(IPAddress.Any, 0);
                    byte[] b = u.Receive(ref e);
                    readData = readData + ASCIIEncoding.UTF32.GetString(b);

                    if (readData.IndexOf('\n') != -1)
                    {
                        Console.WriteLine();
                        Console.WriteLine("BlockStart");
                        Console.WriteLine("=========================");
                        readDatanew = readData.Split('\n')[1];
                        Console.Write("new: " + readDatanew);
                        readData = readData.Split('\n')[0];
                        Console.Write("current: " + readData);
                        Console.WriteLine("=========================");
                        Parser(readData);
                        Console.WriteLine("BlockEnd");
                        readData = readDatanew + '\n';
                    }


                }
                else
                {
                    //GlobalVar.parserdebug_msg_a = "Nothing here!";
                }





            }

        }

        void Parser(string in_raw)
        {
            string in_nochksum = checksum_test(in_raw);
            if (in_nochksum != "falsecrc")
            {
                string in_type = in_nochksum.Remove(2, in_nochksum.Length - 2);
                Console.WriteLine("parser - Type: " + in_type);
                string in_msg = in_nochksum.Remove(0, 2);
                Console.WriteLine("parser - stripped msg: " + in_msg);


                if (in_type == "$P")
                {
                    Console.WriteLine("parser - case: Position");
                    try
                    {

                        string[] values = in_msg.Split(',');

                        GlobalVar.current_loc_lat = (Int32.Parse(values[0], System.Globalization.NumberStyles.HexNumber)) / 10000000F;
                        GlobalVar.current_loc_lon = (Int32.Parse(values[1], System.Globalization.NumberStyles.HexNumber)) / 10000000F;
                        GlobalVar.current_loc_gpsalt = (Int32.Parse(values[2], System.Globalization.NumberStyles.HexNumber)) / 100;
                        GlobalVar.current_numsats = (Int32.Parse(values[3]));
                        GlobalVar.current_gpsstatus = (Int32.Parse(values[4]));
                        GlobalVar.current_fpcase = (Int32.Parse(values[5]));

                        Console.WriteLine("Lat: " + GlobalVar.current_loc_lat);
                        Console.WriteLine("Lon: " + GlobalVar.current_loc_lon);
                        Console.WriteLine("GPSAlt: " + GlobalVar.current_loc_gpsalt);
                        Console.WriteLine("Sats: " + GlobalVar.current_numsats);
                        Console.WriteLine("GPSstatus (2=Fix): " + GlobalVar.current_gpsstatus);



                        WriteTo_tb_lat(Convert.ToString(GlobalVar.current_loc_lat));
                        WriteTo_tb_lon(Convert.ToString(GlobalVar.current_loc_lon));
                        WriteTo_tb_gpsalt(Convert.ToString(GlobalVar.current_loc_gpsalt));
                        WriteTo_tb_numsats(Convert.ToString(GlobalVar.current_numsats));
                        WriteTo_tb_gpsstatus(Convert.ToString(GlobalVar.current_gpsstatus));
                        WriteTo_tb_fpcase(Convert.ToString(GlobalVar.current_fpcase));
                        WriteTo_tb_posupdate("");








                        IFormatProvider EN = new CultureInfo("en-GB");
                        //Random random = new Random();
                        float lat = GlobalVar.current_loc_lat;
                        //lat += GlobalVar.logflightpath_id * 0.00005F * random.Next(-10, 10);

                        float lon = GlobalVar.current_loc_lon;
                        //lon += GlobalVar.logflightpath_id * 0.00005F * random.Next(-10, 10);

                        string latstrEN = lat.ToString(EN);
                        string lonstrEN = lon.ToString(EN);
                        string pathposition = GlobalVar.logflightpath_id + "," + latstrEN + "," + lonstrEN + '\n';

                        if (GlobalVar.current_gpsstatus == 2) //only write output to flightpathfile at GPS-FIX
                        {
                            file_write_flightpath(pathposition);
                            GlobalVar.logflightpath_id++;
                        }




                    }
                    catch { }

                }




                if (in_type == "$A")
                {
                    Console.WriteLine("parser - case: Attitude");
                    try
                    {
                        string[] values = in_msg.Split(',');

                        GlobalVar.current_ahrs_roll = (Int32.Parse(values[0])) / 100F;
                        GlobalVar.current_ahrs_pitch = (Int32.Parse(values[1])) / 100F;
                        GlobalVar.current_ahrs_yaw = (Int32.Parse(values[2])) / 100F;
                        GlobalVar.current_gpshd = (Int32.Parse(values[3])) / 100F;
                        GlobalVar.current_gpsgroundspeed = (Int32.Parse(values[4])) / 100F;
                        GlobalVar.current_distancewp = (Int32.Parse(values[5], System.Globalization.NumberStyles.HexNumber));

                        Image image = new Bitmap("arrow_small.png");
                        Image image2 = new Bitmap("arrow_small_left.png");
                        picbox_gpshd.Image = RotateImage(image, GlobalVar.current_gpshd);
                        picbox_target_hd.Image = RotateImage(image, GlobalVar.current_ahrs_yaw);
                        picbox_ahrs_roll.Image = RotateImage(image, GlobalVar.current_ahrs_roll);
                        picbox_ahrs_pitch.Image = RotateImage(image2, GlobalVar.current_ahrs_pitch);

                        WriteTo_tb_gpshd(Convert.ToString(GlobalVar.current_gpshd));
                        WriteTo_tb_ahrs_yaw(Convert.ToString(GlobalVar.current_ahrs_yaw));
                        WriteTo_tb_ahrs_roll(Convert.ToString(GlobalVar.current_ahrs_roll));
                        WriteTo_tb_ahrs_pitch(Convert.ToString(GlobalVar.current_ahrs_pitch));
                        WriteTo_tb_gpsgroundspeed(Convert.ToString(GlobalVar.current_gpsgroundspeed));
                        WriteTo_tb_distancewp(Convert.ToString(GlobalVar.current_distancewp));

                        WriteTo_tb_attupdate("");



                    }
                    catch { }

                }



                if (in_type == "$H")
                {
                    Console.WriteLine("parser - case: Housekeeping");
                    try
                    {
                        string[] values = in_msg.Split(',');

                        GlobalVar.current_millis = (Int32.Parse(values[0]));
                        GlobalVar.current_parachutetime = (Int32.Parse(values[1]));
                        GlobalVar.current_distancehome = (Int32.Parse(values[2]));
                        GlobalVar.current_ascent_or_launched = (Int32.Parse(values[3]));
                        GlobalVar.current_last_contact_time = (Int32.Parse(values[4]));

                        WriteTo_tb_millis(Convert.ToString(GlobalVar.current_millis));
                        WriteTo_tb_parachutetime(Convert.ToString(GlobalVar.current_parachutetime));
                        WriteTo_tb_distancehome(Convert.ToString(GlobalVar.current_distancehome));
                        WriteTo_tb_ascent_or_launched(Convert.ToString(GlobalVar.current_ascent_or_launched));
                        WriteTo_tb_last_contact_time(Convert.ToString(GlobalVar.current_last_contact_time));
                        


                    }
                    catch { }

                }




                if (in_type == "$I")
                {
                    Console.WriteLine("parser - case: PID I");
                    try
                    {
                        int pidtype = Convert.ToInt32(in_msg.Split(',')[0]);
                        Console.WriteLine("parser - case: PID type: " + pidtype);
                        switch (pidtype)
                        {
                            case 0:
                                Console.WriteLine("parser - case: PID I0");
                                try
                                {
                                    WriteTo_tb_pidlist_fbw(in_msg.Remove(0, 2));
                                }
                                catch { }
                                break;

                            case 1:
                                Console.WriteLine("parser - case: PID I1");
                                try
                                {
                                    WriteTo_tb_pidlist_nav1_stab(in_msg.Remove(0, 2));
                                }
                                catch { }
                                break;
                            case 2:
                                Console.WriteLine("parser - case: PID I2");
                                try
                                {
                                    WriteTo_tb_pidlist_nav1_nav(in_msg.Remove(0, 2));
                                }
                                catch { }
                                break;
                            default:
                                break;
                        }
                    }
                    catch { }
                }

                if (in_type == "$N")
                {
                    Console.WriteLine("parser - case: Descent angles");
                    try
                    {
                        string[] values = in_msg.Split(',');

                        GlobalVar.current_angle = (Int32.Parse(values[0]));
                        GlobalVar.current_course = (Int32.Parse(values[1]));
                        GlobalVar.current_useangle = (Int32.Parse(values[2]));
                        GlobalVar.current_usecourse = (Int32.Parse(values[3]));


                        WriteTo_lb_angle(Convert.ToString(GlobalVar.current_angle));
                        WriteTo_lb_course(Convert.ToString(GlobalVar.current_course));
                        
                    }
                    catch { }

                }


                if (in_type == "$T")
                {
                    Console.WriteLine("parser - case: scalers");
                    try
                    {
                        GlobalVar.current_scalers = in_msg;
                        WriteTo_lb_scalers(GlobalVar.current_scalers);
                    }
                    catch { }

                }



            }
        }

        static string checksum_test(string in_raw)
        {
            try
            {

                if (in_raw.IndexOf('*') != -1)
                {
                    string checksum = in_raw.Split('*')[1];
                    Console.WriteLine("chktest - CHKSUM: " + checksum);
                    string nochcksum = in_raw.Split('*')[0];
                    if (calculate_checksum(nochcksum) == checksum)
                    {
                        Console.WriteLine("chktest - return: " + nochcksum);
                        return (nochcksum);
                    }
                    else
                    {
                        Console.WriteLine("chktest - return: falsecrc");
                        return "falsecrc";
                    }
                }
                else
                {
                    Console.WriteLine("chktest - return: falsecrc (to short)");
                    return "falsecrc";
                }
            }
            catch
            {
                Console.WriteLine("chktest - return: falsecrc (failure in checksum routine)");
                return "falsecrc";
            }

        }





        //Write files
        public static void file_write_flightpath(string indata)
        {
            var fs = File.Open(GlobalVar.logflightpathfile_path, FileMode.Append, FileAccess.Write, FileShare.Read);
            var sw = new StreamWriter(fs);
            sw.AutoFlush = true;
            sw.Write(indata);
            sw.Close();
        }


        //Delegates - Write to Textboxes from other threads

        //Delgegate tb_pidlist_fbw
        public void WriteTo_tb_pidlist_fbw(string value)
        {
            if (InvokeRequired)
            {
                this.Invoke(new Action<string>(WriteTo_tb_pidlist_fbw), new object[] { value });
                return;
            }
            tb_pidlist_fbw.Text = value;
            if (tb_pidlist_fbw.BackColor != Color.LightBlue)
            {
                tb_pidlist_fbw.BackColor = Color.LightBlue;
            }
            else
            {
                tb_pidlist_fbw.BackColor = Color.LightGoldenrodYellow;
            }

        }

        //Delgegate tb_pidlist_nav1_stab
        public void WriteTo_tb_pidlist_nav1_stab(string value)
        {
            if (InvokeRequired)
            {
                this.Invoke(new Action<string>(WriteTo_tb_pidlist_nav1_stab), new object[] { value });
                return;
            }
            tb_pidlist_nav1_stab.Text = value;
            if (tb_pidlist_nav1_stab.BackColor != Color.LightBlue)
            {
                tb_pidlist_nav1_stab.BackColor = Color.LightBlue;
            }
            else
            {
                tb_pidlist_nav1_stab.BackColor = Color.LightGoldenrodYellow;
            }
        }


        //Delgegate tb_pidlist_nav1_nav
        public void WriteTo_tb_pidlist_nav1_nav(string value)
        {
            if (InvokeRequired)
            {
                this.Invoke(new Action<string>(WriteTo_tb_pidlist_nav1_nav), new object[] { value });
                return;
            }
            tb_pidlist_nav1_nav.Text = value;
            if (tb_pidlist_nav1_nav.BackColor != Color.LightBlue)
            {
                tb_pidlist_nav1_nav.BackColor = Color.LightBlue;
            }
            else
            {
                tb_pidlist_nav1_nav.BackColor = Color.LightGoldenrodYellow;
            }
        }


        //Delgegate tb_lat
        public void WriteTo_tb_lat(string value)
        {
            if (InvokeRequired)
            {
                this.Invoke(new Action<string>(WriteTo_tb_lat), new object[] { value });
                return;
            }
            tb_lat.Text = value;
        }

        //Delgegate tb_lon
        public void WriteTo_tb_lon(string value)
        {
            if (InvokeRequired)
            {
                this.Invoke(new Action<string>(WriteTo_tb_lon), new object[] { value });
                return;
            }
            tb_lon.Text = value;
        }

        //Delgegate tb_gpsalt
        public void WriteTo_tb_gpsalt(string value)
        {
            if (InvokeRequired)
            {
                this.Invoke(new Action<string>(WriteTo_tb_gpsalt), new object[] { value });
                return;
            }
            tb_gpsalt.Text = value;
        }

        //Delgegate tb_numsats
        public void WriteTo_tb_numsats(string value)
        {
            if (InvokeRequired)
            {
                this.Invoke(new Action<string>(WriteTo_tb_numsats), new object[] { value });
                return;
            }
            tb_numsats.Text = value;
            if (GlobalVar.current_numsats >= 5) tb_numsats.BackColor = Color.Lime;
            else if (GlobalVar.current_numsats == 4) tb_numsats.BackColor = Color.Yellow;
            else tb_numsats.BackColor = Color.Red;
        }


        //Delgegate tb_gpsstatus
        public void WriteTo_tb_gpsstatus(string value)
        {
            if (InvokeRequired)
            {
                this.Invoke(new Action<string>(WriteTo_tb_gpsstatus), new object[] { value });
                return;
            }
            tb_gpsstatus.Text = value;
            if (GlobalVar.current_gpsstatus == 2) tb_gpsstatus.BackColor = Color.Lime;
            else if (GlobalVar.current_gpsstatus == 1) tb_gpsstatus.BackColor = Color.Yellow;
            else tb_gpsstatus.BackColor = Color.Red;
        }

        //Delgegate tb_fpcase
        public void WriteTo_tb_fpcase(string value)
        {
            if (InvokeRequired)
            {
                this.Invoke(new Action<string>(WriteTo_tb_fpcase), new object[] { value });
                return;
            }
            tb_fpcase.Text = value;
        }




        //Delgegate tb_posupdate
        public void WriteTo_tb_posupdate(string value)
        {
            if (InvokeRequired)
            {
                this.Invoke(new Action<string>(WriteTo_tb_posupdate), new object[] { value });
                return;
            }


            if (tb_posupdate_a.BackColor != Color.Lime)
            {
                tb_posupdate_a.BackColor = Color.Lime;
            }
            else
            {
                tb_posupdate_a.BackColor = Color.White;
            }

            if (tb_posupdate_b.BackColor != Color.White)
            {
                tb_posupdate_b.BackColor = Color.White;
            }
            else
            {
                tb_posupdate_b.BackColor = Color.Lime;
            }


        }

        //Delgegate tb_attupdate
        public void WriteTo_tb_attupdate(string value)
        {
            if (InvokeRequired)
            {
                this.Invoke(new Action<string>(WriteTo_tb_attupdate), new object[] { value });
                return;
            }


            if (tb_attupdate_a1.BackColor != Color.Lime)
            {
                tb_attupdate_a1.BackColor = Color.Lime;
                tb_attupdate_a2.BackColor = Color.Lime;
                tb_attupdate_b1.BackColor = Color.White;
                tb_attupdate_b2.BackColor = Color.White;
            }
            else
            {
                tb_attupdate_a1.BackColor = Color.White;
                tb_attupdate_a2.BackColor = Color.White;
                tb_attupdate_b1.BackColor = Color.Lime;
                tb_attupdate_b2.BackColor = Color.Lime;
            }

        }



        //Delgegate tb_gpshd
        public void WriteTo_tb_gpshd(string value)
        {
            if (InvokeRequired)
            {
                this.Invoke(new Action<string>(WriteTo_tb_gpshd), new object[] { value });
                return;
            }
            tb_gpshd.Text = value;
        }

        //Delgegate tb_ahrs_yaw
        public void WriteTo_tb_ahrs_yaw(string value)
        {
            if (InvokeRequired)
            {
                this.Invoke(new Action<string>(WriteTo_tb_ahrs_yaw), new object[] { value });
                return;
            }
            tb_target_hd.Text = value;
        }

        
        //Delgegate tb_ahrs_roll
        public void WriteTo_tb_ahrs_roll(string value)
        {
            if (InvokeRequired)
            {
                this.Invoke(new Action<string>(WriteTo_tb_ahrs_roll), new object[] { value });
                return;
            }
            tb_ahrs_roll.Text = value;
        }

        //Delgegate tb_ahrs_pitch
        public void WriteTo_tb_ahrs_pitch(string value)
        {
            if (InvokeRequired)
            {
                this.Invoke(new Action<string>(WriteTo_tb_ahrs_pitch), new object[] { value });
                return;
            }
            tb_ahrs_pitch.Text = value;
        }




        //Delgegate tb_gpsgroundspeed
        public void WriteTo_tb_gpsgroundspeed(string value)
        {
            if (InvokeRequired)
            {
                this.Invoke(new Action<string>(WriteTo_tb_gpsgroundspeed), new object[] { value });
                return;
            }
            tb_gpsgroundspeed.Text = value;
        }

        //Delgegate tb_distancewp
        public void WriteTo_tb_distancewp(string value)
        {
            if (InvokeRequired)
            {
                this.Invoke(new Action<string>(WriteTo_tb_distancewp), new object[] { value });
                return;
            }
            tb_distancewp.Text = value;
        }


        //Delgegate tb_millis
        public void WriteTo_tb_millis(string value)
        {
            if (InvokeRequired)
            {
                this.Invoke(new Action<string>(WriteTo_tb_millis), new object[] { value });
                return;
            }
            tb_millis.Text = String.Format("{0:0.##}", (Convert.ToInt32(value)/60.0));
        }


        //Delgegate tb_parachutetime
        public void WriteTo_tb_parachutetime(string value)
        {
            if (InvokeRequired)
            {
                this.Invoke(new Action<string>(WriteTo_tb_parachutetime), new object[] { value });
                return;
            }
            tb_parachutetime.Text = value;
            if (Convert.ToInt32(value) > 0)
            {
                tb_parachutetime.BackColor = Color.Red;
            }
            if (value == "-1")
            {
                tb_parachutetime.BackColor = Color.Lime;
            }

        }

        //Delgegate tb_distancehome
        public void WriteTo_tb_distancehome(string value)
        {
            if (InvokeRequired)
            {
                this.Invoke(new Action<string>(WriteTo_tb_distancehome), new object[] { value });
                return;
            }
            tb_distancehome.Text = value;
        }

        //Delgegate tb_ascent_or_launched
        public void WriteTo_tb_ascent_or_launched(string value)
        {
            if (InvokeRequired)
            {
                this.Invoke(new Action<string>(WriteTo_tb_ascent_or_launched), new object[] { value });
                return;
            }
            tb_ascent_or_launched.Text = value;
        }

        //Delgegate tb_last_contact_time
        public void WriteTo_tb_last_contact_time(string value)
        {
            if (InvokeRequired)
            {
                this.Invoke(new Action<string>(WriteTo_tb_last_contact_time), new object[] { value });
                return;
            }
            tb_last_contact_time.Text = value;
            if (Convert.ToInt32(value) <= 2)
            {
                tb_last_contact_time.BackColor = Color.LimeGreen;
            }
            if (Convert.ToInt32(value) > 2 && Convert.ToInt32(value) <= 5)
            {
                tb_last_contact_time.BackColor = Color.Orange;
            }
            if (Convert.ToInt32(value) > 5 && Convert.ToInt32(value) <= 10)
            {
                tb_last_contact_time.BackColor = Color.OrangeRed;
            }
            if (Convert.ToInt32(value) > 10)
            {
                tb_last_contact_time.BackColor = Color.Red;
            }

        }

        //Delgegate lb_angle
        public void WriteTo_lb_angle(string value)
        {
            if (InvokeRequired)
            {
                this.Invoke(new Action<string>(WriteTo_lb_angle), new object[] { value });
                return;
            }
            lb_angle.Text = value;
            if (GlobalVar.current_useangle == 1) lb_angle.BackColor = Color.LimeGreen;
            else lb_angle.BackColor = Color.Red;
        }

        //Delgegate lb_course
        public void WriteTo_lb_course(string value)
        {
            if (InvokeRequired)
            {
                this.Invoke(new Action<string>(WriteTo_lb_course), new object[] { value });
                return;
            }
            lb_course.Text = value;
            if (GlobalVar.current_usecourse == 1) lb_course.BackColor = Color.LimeGreen;
            else lb_course.BackColor = Color.Red;
        }


        //Delgegate lb_scalers
        public void WriteTo_lb_scalers(string value)
        {
            if (InvokeRequired)
            {
                this.Invoke(new Action<string>(WriteTo_lb_scalers), new object[] { value });
                return;
            }
            lb_scalers.Text = value;
            if (GlobalVar.current_usecourse == 1) lb_scalers.BackColor = Color.LimeGreen;
            else lb_scalers.BackColor = Color.Red;
        }





        //read last flighpath ID of flightpathfile
        public static int GetFlightPathID()
        {
            int id = 0;

            using (StreamReader sr = new StreamReader(GlobalVar.logflightpathfile_path))
            {

                while (!sr.EndOfStream)
                {
                    string line = sr.ReadLine();
                    if (sr.Peek() == -1)
                    {
                        Console.WriteLine(" this is the last line");
                        Console.WriteLine(line);
                        string[] idstring = line.Split(',');
                        id = Convert.ToInt32(idstring[0]);
                    }
                }
            }

            return id;

        }


        //rotate Images
        public static Bitmap RotateImage(Image image, float angle)
        {
            // center of the image
            float rotateAtX = image.Width / 2;
            float rotateAtY = image.Height / 2;
            bool bNoClip = false;
            return RotateImage(image, rotateAtX, rotateAtY, angle, bNoClip);
        }

        public static Bitmap RotateImage(Image image, float angle, bool bNoClip)
        {
            // center of the image
            float rotateAtX = image.Width / 2;
            float rotateAtY = image.Height / 2;
            return RotateImage(image, rotateAtX, rotateAtY, angle, bNoClip);
        }

        public static Bitmap RotateImage(Image image, float rotateAtX, float rotateAtY, float angle, bool bNoClip)
        {
            int W, H, X, Y;
            if (bNoClip)
            {
                double dW = (double)image.Width;
                double dH = (double)image.Height;

                double degrees = Math.Abs(angle);
                if (degrees <= 90)
                {
                    double radians = 0.0174532925 * degrees;
                    double dSin = Math.Sin(radians);
                    double dCos = Math.Cos(radians);
                    W = (int)(dH * dSin + dW * dCos);
                    H = (int)(dW * dSin + dH * dCos);
                    X = (W - image.Width) / 2;
                    Y = (H - image.Height) / 2;
                }
                else
                {
                    degrees -= 90;
                    double radians = 0.0174532925 * degrees;
                    double dSin = Math.Sin(radians);
                    double dCos = Math.Cos(radians);
                    W = (int)(dW * dSin + dH * dCos);
                    H = (int)(dH * dSin + dW * dCos);
                    X = (W - image.Width) / 2;
                    Y = (H - image.Height) / 2;
                }
            }
            else
            {
                W = image.Width;
                H = image.Height;
                X = 0;
                Y = 0;
            }

            //create a new empty bitmap to hold rotated image
            Bitmap bmpRet = new Bitmap(W, H);
            bmpRet.SetResolution(image.HorizontalResolution, image.VerticalResolution);

            //make a graphics object from the empty bitmap
            Graphics g = Graphics.FromImage(bmpRet);

            //Put the rotation point in the "center" of the image
            g.TranslateTransform(rotateAtX + X, rotateAtY + Y);

            //rotate the image
            g.RotateTransform(angle);

            //move the image back
            g.TranslateTransform(-rotateAtX - X, -rotateAtY - Y);

            //draw passed in image onto graphics object
            g.DrawImage(image, new PointF(0 + X, 0 + Y));

            return bmpRet;
        }

        private void bt_delay30s_Click(object sender, EventArgs e)
        {
            Form1.UdpSend("$RDELAY30");
        }

        private void bt_delay60s_Click(object sender, EventArgs e)
        {
            Form1.UdpSend("$RDELAY60");
        }

        private void bt_delay120s_Click(object sender, EventArgs e)
        {
            Form1.UdpSend("$RDELAY120");
        }

        private void bt_cancel_parachute_Click(object sender, EventArgs e)
        {
            Form1.UdpSend("$RCANCEL");
        }

        
        private void bt_gsfbw_Click(object sender, EventArgs e)
        {
            Form5_GS_FBW form5 = new Form5_GS_FBW();
            form5.Show();
            
            
        }

        private void bt_releasepara_Click(object sender, EventArgs e)
        {
            Form4 form4 = new Form4();
            form4.Show();
        }

        private void bt_launchglider_Click(object sender, EventArgs e)
        {
            Form6 form6 = new Form6();
            form6.Show();
            
        }

        private void bt_set_fixedangle_Click(object sender, EventArgs e)
        {
            string no_chksum = "$D" + tb_fixed_angle.Text + "," + tb_fixed_heading.Text;
            string udpsendstring = no_chksum + "*" + Form1.calculate_checksum(no_chksum);
            Form1.UdpSend(udpsendstring);
        }

        private void bt_use_angle_Click(object sender, EventArgs e)
        {
            string no_chksum = "$E1";
            string udpsendstring = no_chksum + "*" + Form1.calculate_checksum(no_chksum);
            Form1.UdpSend(udpsendstring);
        }

        private void bt_use_course_Click(object sender, EventArgs e)
        {
            string no_chksum = "$F1";
            string udpsendstring = no_chksum + "*" + Form1.calculate_checksum(no_chksum);
            Form1.UdpSend(udpsendstring);
        }

        private void bt_unuse_angle_Click(object sender, EventArgs e)
        {
            string no_chksum = "$E0";
            string udpsendstring = no_chksum + "*" + Form1.calculate_checksum(no_chksum);
            Form1.UdpSend(udpsendstring);
        }

        private void bt_unuse_course_Click(object sender, EventArgs e)
        {
            string no_chksum = "$F0";
            string udpsendstring = no_chksum + "*" + Form1.calculate_checksum(no_chksum);
            Form1.UdpSend(udpsendstring);
        }

        private void bt_getscalers_Click(object sender, EventArgs e)
        {
            string no_chksum = "$S";
            string udpsendstring = no_chksum + "*" + Form1.calculate_checksum(no_chksum);
            Form1.UdpSend(udpsendstring);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string no_chksum = "$V" + tb_telescaler.Text;
            string udpsendstring = no_chksum + "*" + Form1.calculate_checksum(no_chksum);
            Form1.UdpSend(udpsendstring);
        }

        private void bt_reset_launch_Click(object sender, EventArgs e)
        {
            GlobalVar.udpsendstring = "$RASCENTON";
            Form3 form3 = new Form3();
            form3.Show();
        }

        private void bt_ascent_off_Click(object sender, EventArgs e)
        {
            GlobalVar.udpsendstring = "$RASCENTOFF";
            Form3 form3 = new Form3();
            form3.Show();
        }

        private void bt_smoke1_Click(object sender, EventArgs e)
        {
            string no_chksum = "$RSMOKER111";
            string udpsendstring = no_chksum;
            Form1.UdpSend(udpsendstring);                    
        }

        private void bt_smoke2_Click(object sender, EventArgs e)
        {
            string no_chksum = "$RSMOKER222";
            string udpsendstring = no_chksum;
            Form1.UdpSend(udpsendstring);
        }

        private void bt_smokeoff_Click(object sender, EventArgs e)
        {
            string no_chksum = "$RSMOKEROFF";
            string udpsendstring = no_chksum;
            Form1.UdpSend(udpsendstring);
        }

        


      

        

        

        
























    }
}
